package com.losdun.product.utils;

import com.losdun.common.core.domain.TreeEntity;
import com.losdun.common.utils.StringUtils;
import com.losdun.product.domain.BaseTreeEntity;
import com.losdun.product.domain.Category;
import com.losdun.product.domain.vo.TreeSelectVo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sword.ye
 * @date 2025/3/1
 **/
public class TreeSelectBuilder<T extends BaseTreeEntity> {


    public List<TreeSelectVo> buildTree(List<T> dataList) {
        List<T> categoryTrees= this.buildTreeList(dataList);
        return categoryTrees.stream().map(TreeSelectVo::new).collect(Collectors.toList());
    }
    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    private  List<T> buildTreeList(List<T> dataList)
    {
        List<T> returnList = new ArrayList<T>();
        List<Long> tempList = dataList.stream().map(t -> t.getId()).collect(Collectors.toList());
        for (T obj : dataList)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(obj.getParentId()))
            {
                recursionFn(dataList, obj);
                returnList.add(obj);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = dataList;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<T> list, T t)
    {
        // 得到子节点列表
        List<T> childList = getChildList(list, t);
        t.setChildren(childList);
        for (T tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<T> getChildList(List<T> list, T t)
    {
        List<T> tlist = new ArrayList<T>();
        Iterator<T> it = list.iterator();
        while (it.hasNext())
        {
            T n = (T) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<T> list, T t)
    {
        return getChildList(list, t).size() > 0;
    }
}
